<!--  -->
<template>
  <div class="wrap">
    <div class="divsearch">
      <input
        class="search"
        v-model="searchval"
        v-on:keyup.enter="search()"
        placeholder="请输入关键词"
      />
    </div>
    <div class="chart">
      <div id="container" class="chart1"></div>
    </div>
  </div>
</template>

<script>
import G6 from "@antv/g6";
import axios from "axios";
export default {
  name: "",
  components: {},
  props: [],
  data() {
    return {
      graph: undefined,
      tooltip: undefined,
      protocol: "bolt",
      host: "172.16.218.125",
      port: 7687,
      username: "neo4j",
      password: "123456",
      searchval: "",
      echartsData: [],
      Colors: { noun: "#588c73", adj: "#f2e394", v: "#d96459", adv: "#f2ae72" },
      datalist: {
        nodes: [],
        // 边集
        edges: [],
      },
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // this.init()

    //this.getdata(this.searchval);
    this.query(this.searchval);
  },
  methods: {
    connect() {
      return this.$neo4j
        .connect(
          this.protocol,
          this.host,
          this.port,
          this.username,
          this.password
        )
        .then((driver) => {
          // Update the context of your app
        });
    },
    query(name) {
    
      this.connect();
      let cypher = `match p=(n:person)-[]->(m:person)  return  p `;
      if (name) {
        cypher = `match p=(n)-[]->(m) where n.name='${name}'  return  p `;
      }
      this.$neo4j.run(cypher).then((res) => {
          console.log("555", res);
          let records = res.records;
          let nodes = new Set();
          this.nodesRelation = [];
          for (let i = 0; i < records.length; i++) {
            nodes.add({
              id:records[i]._fields[0].segments[0].start.properties.name,
              label: records[i]._fields[0].segments[0].start.properties.name,
              info: records[i]._fields[0].segments[0].start.properties.info,
            });
            nodes.add({
              id:records[i]._fields[0].segments[0].end.properties.name,
              label: records[i]._fields[0].segments[0].end.properties.name,
              info: records[i]._fields[0].segments[0].end.properties.info,
            });
            this.nodesRelation.push({
              source: records[i]._fields[0].segments[0].start.properties.name,
              target: records[i]._fields[0].segments[0].end.properties.name,
              label: records[i]._fields[0].segments[0].relationship.type,
            });
          }
          this.datalist.edges = this.nodesRelation;
          console.log("this.nodesRelation", this.nodesRelation);
          var bb = [];
          bb = [...nodes];
          console.log("bb", bb);
          var aa = [];
          this.echartsData = [];
          aa = Array.from(new Set(bb.map((item) => JSON.stringify(item)))).map(
            (item) => JSON.parse(item)
          );
          console.log("node", aa);
          aa.forEach((e) => {
            this.echartsData.push({
              name: e.name,
            });
          });
          console.log("this.echartsData", this.echartsData);
          this.datalist.nodes = aa;

          this.initantv();
        }).then(() => {});
    },
     search(){
     
     this.datalist.nodes=[];
     this.datalist.edges=[];
       
      this.query(this.searchval)
      
    },
    inittooltip() {
      this.tooltip = new G6.Tooltip({
        offsetX: 10,
        offsetY: 10,
        fixToNode: [1, 0.5],
        // the types of items that allow the tooltip show up
        // 允许出现 tooltip 的 item 类型
        itemTypes: ["node", "edge"],
        // custom the tooltip's content
        // 自定义 tooltip 内容
        getContent: (e) => {
          const outDiv = document.createElement("div");
          outDiv.style.width = "fit-content";
          outDiv.style.height = "fit-content";
          const model = e.item.getModel();
          if (e.item.getType() === "node") {
            outDiv.innerHTML = `${model.name}`;
          } else {
            const source = e.item.getSource();
            const target = e.item.getTarget();
            outDiv.innerHTML = `来源：${source.getModel().name}<br/>去向：${
              target.getModel().name
            }`;
          }
          return outDiv;
        },
      });
    },
    initantv() {
      const container = document.getElementById("container");
      const width = container.scrollWidth;
      const height = container.scrollHeight || 900;
      if(this.graph){
       
        this.graph.data(this.datalist);
        this.datalist.nodes.forEach((i) => {
        i.style = {
          fill: this.randomColor(),
        };
      });
        this.graph.render(); // 渲染图
        return
      }
      // this.inittooltip()
      this.graph = new G6.Graph({
        container: "container",
        width: width,
        height: height,
        // fitView: true,
        layout: {
          type: "force",
          linkDistance: 250, // 可选，边长
          nodeStrength: 30, // 可选
          // edgeStrength: 0.1, // 可选
          //nodeSize: 40, // 可选
          preventOverlap: true,
          edgeStrength: 0.7,
        },
        // plugins: [this.tooltip],
        defaultNode: {
          size: 30,
          labelCfg: {
            // 节点上的标签文本样式配置
            style: {
              fill: "#fff", // 节点标签文字颜色
              fontSize: 10,
            },
          },
        },
        defaultEdge: {
          // ...                 // 边的其他配置
          // 边样式配置
          style: {
            //opacity: 0.6, // 边透明度
            // stroke: 'grey', // 边描边颜色
            //  endArrow: true,
          },
          // 边上的标签文本配置
          labelCfg: {
            autoRotate: true, // 边上的标签文本根据边的方向旋转
            style: {
              //opacity: 0.6, // 边透明度
              // stroke: 'grey', // 边描边颜色
              fontSize: 10,
              fill: "#fff",
            },
          },
        },

        // 内置交互
        modes: {
          default: ["drag-canvas", "zoom-canvas", "drag-node"],
        },
      });
      console.log("444", this.datalist);
      this.graph.data(this.datalist); // 读取 Step 2 中的数据源到图上
      this.datalist.nodes.forEach((i) => {
        i.style = {
          fill: this.randomColor(),
        };
      });
      this.graph.render(); // 渲染图
      // 监听鼠标进入节点
      this.graph.on("node:dragstart", (e) => {
        this.graph.layout();
        refreshDragedNodePosition(e);
      });
      this.graph.on("node:drag", (e) => {
        const forceLayout = this.graph.get("layoutController").layoutMethods[0];
        forceLayout.execute();
        refreshDragedNodePosition(e);
      });
      this.graph.on("node:dragend", (e) => {
        e.item.get("model").fx = null;
        e.item.get("model").fy = null;
      });

      if (typeof window !== "undefined")
        window.onresize = () => {
          if (!this.graph || this.graph.get("destroyed")) return;
          if (!container || !container.scrollWidth || !container.scrollHeight)
            return;
          this.graph.changeSize(container.scrollWidth, container.scrollHeight);
        };
      function refreshDragedNodePosition(e) {
        const model = e.item.get("model");
        model.fx = e.x;
        model.fy = e.y;
      }

      // 鼠标进入节点
      // this.graph.on("node:mouseenter", (e) => {
      //   const nodeItem = e.item; // 获取鼠标进入的节点元素对象
      //   console.log("鼠标移入", nodeItem._cfg);
      // });
      // 单击节点
      this.graph.on("node:click", (e) => {
        const nodeItem = e.item; // 获取被点击的节点元素对象
        console.log("单击", nodeItem._cfg);
      });
      // 双击节点
      this.graph.on("node:dblclick", (e) => {
        const nodeItem = e.item; // 获取被点击的节点元素对象
        console.log("双击", nodeItem._cfg.id);
        this.search1(nodeItem._cfg.id);
      });
    },

    randomColor() {
      const colors = [
        "#F4AB87",
        "#EEC88D",
        "#76CADF",
        "#97DA9D",
        "#88DCD8",
        "#FB7F89",
        "#F0E403",
        "#F576BE",
        "#ACADFF",
        "#7EC3FB",
        "#D0DB02",
        "#C07B11",
        "#00ACC2",
        "#2AAD41",
        "#A59D00",
        "#EB4747",
        "#CD0EBD",
        "#DE3997",
        "#1f77b4",
        "#ff7f0e",
        "#2ca02c",
        "#d62728",
        "#9467bd",
        "#8c564b",
        "#e377c2",
        "#7f7f7f",
        "#bcbd22",
        "#17becf",
      ];
      return colors[Math.floor(Math.random() * colors.length)];
    },

    async search1(val) {
      //alert(111)
      //  this.datalist.nodes=[];
      //  this.datalist.edges=[];
      var cc = await axios.get(
        "https://api.ownthink.com/kg/knowledge?entity=" + val
      );
      var dd = cc.data.data.avp;
      if (dd) {
        for (let i = 0; i < dd.length; i++) {
          var ee = {
            id: dd[i][1],
            label: dd[i][1],
          };

          var ff = {
            source: dd[i][1],
            target: val,
            label: dd[i][0],
          };
          this.datalist.nodes.push(ee);
          this.datalist.edges.push(ff);
        }
        this.datalist.nodes.push({ id: val, label: val });
        console.log("444", this.datalist);
        this.graph.data(this.datalist); // 读取 Step 2 中的数据源到图上
        this.datalist.nodes.forEach((i) => {
          i.style = {
            fill: this.randomColor(),
          };
        });
        this.graph.render(); // 渲染图
      }
    },
  },
};
</script>
<style lang='css'>
* {
  margin: 0;
  padding: 0;
}
.wrap {
  width: 100%;
  /* position: relative; */
  background-color: #11162a;
}
.divsearch {
  margin: 0 auto;
  text-align: center;
  padding-top: 10px;
}
.wrap .search {
  /* position: absolute;
  left: 50%; */

  width: 640px;
  /* transform: translate(-50%); */
  text-align: center;
  font-size: 18px;
  line-height: 46px;
  border-radius: 100px;
  border: none;
  outline: none;
}

.wrap .chart .chart1 {
  /* position: absolute;  */
  width: 100%;
  height: 100%;
}
</style>